﻿package com.fluidsoftwarellc.xon
{
	import com.fluidsoftwarellc.xon.events.XONLoaderEvent;
	import flash.events.EventDispatcher;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	/**
	 * ...
	 * @author Scott Tompkins
	 * FXON (Flash XML Object Notation) and Parser (http://code.google.com/p/as3-fxon/)
	 * Copyright (C) 2011  Scott C. Tompkins
	 * 
	 * This program is free software: you can redistribute it and/or modify
	 * it under the terms of the GNU General Public License as published by
	 * the Free Software Foundation, either version 3 of the License, or
	 * (at your option) any later version.
	 * 
	 * This program is distributed in the hope that it will be useful,
	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	 * GNU General Public License for more details.
	 * 
	 * You should have received a copy of the GNU General Public License
	 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
	 */
	public class XONLoader extends EventDispatcher
	{
		private var _xmlLoader:URLLoader;
		private var _xmlPath:String;
		private var _objectName:String;
		
		
		public function XONLoader(xmlPath:String, objectName:String) 
		{
			_xmlPath = xmlPath;
			_objectName = objectName;
			
			_xmlLoader = new URLLoader();
			_xmlLoader.addEventListener(Event.COMPLETE, parseXMLData);		
			
		}
		
		public function loadXON():void
		{
			_xmlLoader.load(new URLRequest(_xmlPath));
		}
		
		private function parseXMLData(evt:Event):void 
		{
			var xmlData:XML = new XML(evt.target.data);
			var found:Boolean = false;
			for each (var xmlObject:XML in xmlData.children()) {
				if (xmlObject.attribute("name") == _objectName) {
					found = true;
					var object:Object = XONParser.parseXONObject(xmlObject) as Object;
					var evtComplete:XONLoaderEvent = new XONLoaderEvent(XONLoaderEvent.LOADER_COMPLETE, object);
					dispatchEvent(evtComplete);					
					break;
				}
			}
			
			if (!found) {
				trace("Object with name: " + "'" + _objectName + "' not found in '" + _xmlPath + "'");
			}
		}
		
		
	}

}